/**
 * 
 */
package idv.takeshi.software.productline.bookstore.presentation.web.controller;

import java.util.Arrays;
import java.util.List;

import idv.takeshi.software.productline.bookstore.application.service.BrowseBooksService;
import idv.takeshi.software.productline.bookstore.domain.model.book.Book;
import idv.takeshi.software.productline.bookstore.domain.model.shoppingcart.ShoppingCart;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;

/**
 * A Controller for shopping cart operations.
 * @author takeshi
 *
 */
@Controller("shoppingCartController")
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
	
	@Autowired
	private BrowseBooksService browseBooksService;
	
	@RequestMapping(value = "/addBook.html", method = RequestMethod.GET)
	public String addBook(@RequestParam Long bookId, WebRequest request){
		Book book = null;
		ShoppingCart shoppingCart = (ShoppingCart) request.getAttribute(
				"shoppingCart", WebRequest.SCOPE_SESSION);
		book = this.browseBooksService.getBookById(bookId);
		shoppingCart.addBook(book);
		return "redirect:/shoppingCart/shoppingCart.html";
	}
	
	@RequestMapping(value = "/updateQuantities.html", method = RequestMethod.POST)
	public String updateQuantities(
			@RequestParam Long[] bookIds, @RequestParam Integer[] quantities, 
			WebRequest request){
		
		ShoppingCart shoppingCart = (ShoppingCart) request.getAttribute(
				"shoppingCart", WebRequest.SCOPE_SESSION);
		if(ArrayUtils.isNotEmpty(bookIds)){
			Book book = null;
			Long id = null;
			for(int a = 0; a < bookIds.length; a++){
				id = bookIds[a];
				book = this.browseBooksService.getBookById(id);
				shoppingCart.updateQuantity(book, quantities[a]);
			}
		}
		return "redirect:/shoppingCart/shoppingCart.html";
	}
	
	@RequestMapping(value = "/removeBook.html", method = RequestMethod.GET)
	public String removeBook(@RequestParam Long bookId, WebRequest request){
		ShoppingCart shoppingCart = (ShoppingCart) request.getAttribute(
				"shoppingCart", WebRequest.SCOPE_SESSION);
		Book book = this.browseBooksService.getBookById(bookId);
		shoppingCart.removeBook(book);
		return "redirect:/shoppingCart/shoppingCart.html";
	}
	
}
